package com.example.victory.service;

import com.example.victory.entity.companyEntity.LossWarningEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.swagger.handler.MiniAppWarningApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.AnalysisUtils;
import com.example.victory.utils.CrmUtils;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.*;;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.cgws.fintech.sdk.common.utils.JsonHelper;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class MiniAppLossWarningService implements MiniAppWarningApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private SessionService sessionService;

    @Override
    public ResponseEntity<ApiResponseLossWarning> getLossWarning(ApiRequestLossWarning param) {
        ApiRequestLossWarningData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        ApiRequestLossWarningData.LossTypeEnum lossType = data.getLossType();
        ServiceHelper.checkDataNotNull(lossType, "lossType");
        Integer index = data.getIndex();
        Integer pageSize = data.getPageSize();
        if (index == null) index = 0; // 首页
        if (pageSize == null) pageSize = 20; // 默认20条

        // 获取当前用户
        User user = sessionService.getCurrentUserSession(true).getUser();
        String crmId = user.getCrmId();
        if (crmId == null) crmId = "";

        ApiResponseLossWarningData lossWarningData = new ApiResponseLossWarningData();
        List<LossWarningCustInfo> custInfoList = new ArrayList<>();
        List<ApiRequestCustomerQueryData> customerQueryDataList = Lists.newArrayList();

        Integer nowDate = Integer.valueOf(DateHelper.getDateYYYYMMDD(new Date()));
        if (Objects.equals(lossType, ApiRequestLossWarningData.LossTypeEnum.BIG_ROLL_OUT)) { // 大比例转出
            // 获取往前第30个交易日的日期
            Integer beforeTradeDay = customerMapper.getTradingDay(nowDate,30);
            List<LossWarningEntity> bigRollOutEntities = customerMapper.getCustLossWarnBigRollOutPage(crmId, index * pageSize, (index + 1) * pageSize, beforeTradeDay, nowDate);
            if (bigRollOutEntities == null || bigRollOutEntities.size() == 0) {
                lossWarningData.setItems(Collections.emptyList());
                return ResponseEntity.ok(new ApiResponseLossWarning().data(lossWarningData));
            }

            bigRollOutEntities.forEach(entity -> {
                ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
                customerQueryData.setCustNum(entity.getCustomerId());
                customerQueryDataList.add(customerQueryData);

                LossWarningCustInfo custInfo = new LossWarningCustInfo();
                custInfo.setName(entity.getName());
                custInfo.setCustomerId(entity.getCustomerId());
                custInfo.setPhone(entity.getPhone());
                custInfo.setCustLevel(entity.getCustLevel());
                custInfo.setRelationType(AnalysisUtils.getRelationType(entity.getRelationType()));
                if (entity.getRiskLevel() != null) custInfo.setRiskLevel(entity.getRiskLevel());

                ArrayList<KeyValueDetail> keyValueList = Lists.newArrayList();

                KeyValueDetail total = new KeyValueDetail();
                total.setName("总资产");
                total.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getTotal().trim())));
                keyValueList.add(total);

                KeyValueDetail outflowMoney = new KeyValueDetail();
                outflowMoney.setName("流出金额");
                outflowMoney.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getOutflowMoney().trim())));
                keyValueList.add(outflowMoney);

                KeyValueDetail outflowRate = new KeyValueDetail();
                outflowRate.setName("流出比例");
                outflowRate.setValue(entity.getOutflowRate().trim());
                keyValueList.add(outflowRate);

                KeyValueDetail outflowDate = new KeyValueDetail();
                outflowDate.setName("流出日期");
                outflowDate.setValue(entity.getOutflowDate());
                keyValueList.add(outflowDate);

                custInfo.setDetails(keyValueList);
                custInfoList.add(custInfo);
            });

        } else { // 转托管
            // 获取往前第30个交易日的日期
            Integer beforeTradeDay = customerMapper.getTradingDay(nowDate,30);
            List<LossWarningEntity> turnToHostEntities = customerMapper.getCustLossWarnturnToHostPage(crmId, index * pageSize, (index + 1) * pageSize, beforeTradeDay, nowDate);
            if (turnToHostEntities == null || turnToHostEntities.size() == 0) {
                lossWarningData.setItems(Collections.emptyList());
                return ResponseEntity.ok(new ApiResponseLossWarning().data(lossWarningData));
            }

            turnToHostEntities.forEach(entity -> {
                ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
                customerQueryData.setCustNum(entity.getCustomerId());
                customerQueryDataList.add(customerQueryData);

                LossWarningCustInfo custInfo = new LossWarningCustInfo();
                custInfo.setName(entity.getName());
                custInfo.setCustomerId(entity.getCustomerId());
                custInfo.setPhone(entity.getPhone());
                custInfo.setCustLevel(entity.getCustLevel());
                custInfo.setRelationType(AnalysisUtils.getRelationType(entity.getRelationType()));
                if (entity.getRiskLevel() != null) custInfo.setRiskLevel(entity.getRiskLevel());

                ArrayList<KeyValueDetail> keyValueList = Lists.newArrayList();

                KeyValueDetail total = new KeyValueDetail();
                total.setName("总资产");
                total.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getTotal().trim())));
                keyValueList.add(total);

                KeyValueDetail tpye = new KeyValueDetail();
                tpye.setName("类别");
                tpye.setValue(entity.getType());
                keyValueList.add(tpye);

                KeyValueDetail shareholders = new KeyValueDetail();
                shareholders.setName("股东号");
                shareholders.setValue(entity.getShareholders());
                keyValueList.add(shareholders);

                KeyValueDetail happenDate = new KeyValueDetail();
                happenDate.setName("发生日期");
                happenDate.setValue(entity.getHappenDate());
                keyValueList.add(happenDate);

                custInfo.setDetails(keyValueList);
                custInfoList.add(custInfo);
            });
        }
        if(customerQueryDataList.size()>0) {
            List<CustomerAccount> customerAccountList = CrmUtils.getCustAccountListByIds(mvpLoginService, customerQueryDataList);
            if (customerAccountList != null) {
                custInfoList.stream().forEach(customer -> {
                    customerAccountList.forEach(customerAccount -> {
                        if (!StringUtils.isEmpty(customerAccount.getFcid()) && customer.getCustomerId().equals(customerAccount.getCustNum())) {
                            customer.setImId(customerAccount.getFcid());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(new ApiResponseLossWarning().data(lossWarningData.items(custInfoList)));
    }
}
